package com.jams.goodox.utils;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.RelativeSizeSpan;

import java.text.DecimalFormat;

/**
 * Created by jams on 2017/6/26.
 * ***
 * Tel: ***
 */

public class MoneyUtils {

    //保留两位小数
    public static String strToD2(String str){
        if(TextUtils.isEmpty(str)){
            str = "0.00";
        }
        return withSpaceMoney(doubleToString(stringToDouble(str)));
    }

    /**
     * 处理double类型，保留两位小数
     *
     * @param dou 传入的double值
     * @return 保留两位小数的字符串
     */
    public static String doubleToString(Double dou) {
        if (dou == null) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        return df.format(dou);
    }

    //字符串转Double
    public static Double stringToDouble(String string) {
        try {
            return Double.parseDouble(string);
        } catch (Exception e) {
            return 0.00;
        }
    }

    //获取一个普通的带金额 符号的
    public static String withMoney(String money) {
        if (TextUtils.isEmpty(money)) {
            return "¥";
        }
        return "¥" + money;
    }

    //获取一个普通的带金额 符号的
    public static String withMoney(double money) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return "¥" + df.format(money);
    }

    //获取一个普通的带金额 符号的,金额和符号之间有空格
    public static String withSpaceMoney(String money) {
        if (TextUtils.isEmpty(money)) {
            return "¥";
        }
        return "¥ " + money;
    }

    //获取一个普通的带金额 符号的,金额和符号之间有空格
    public static String withSpaceMoney(double money) {
        DecimalFormat df = new DecimalFormat("######0.00");
        return "¥ " + df.format(money);
    }

    /**
     * 显示不同大小的字符串
     *
     * @param unit 單位
     * @param text
     * @return
     */
    public static SpannableStringBuilder getPriceStyle(Double text, String unit) {
        String price;
        SpannableStringBuilder spannable;
        price = doubleToString(text);
        String priceStr = "¥" + price + unit;
        spannable = new SpannableStringBuilder(priceStr);//用于可变字符串
        CharacterStyle span_1 = new RelativeSizeSpan(1.5f);
        spannable.setSpan(span_1, 1, String.valueOf(text.intValue()).length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannable;
    }
}
